<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
  <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
  <style type="text/css">
    .highlight { display: block; background-color: #ddd; }
  </style>
  <script type="text/javascript">
    function highlight() {
      document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
    }
  </script>
</head>
<body onload="prettyPrint(); highlight();">
  <pre class="prettyprint lang-js">&lt;?php
namespace Library\Dal\Driver\Mysql;

<span id='Library-Dal-Driver-Mysql-ActiveRecord'>/**
</span> * ActiveRecord
 * 
 * @class Library.Dal.Driver.Mysql.ActiveRecord
 */
class ActiveRecord implements \Library\Dal\ActiveRecordInterface
{
	private $_query;
	
	private $_parameters = array();
	
	private $_type;
	
<span id='Library-Dal-Driver-Mysql-ActiveRecord-property-_parenthese'>	/**
</span>	 * If parenthese is 0, nothing will happen, if it is 1 an open parenthese will be included in the next method.
	 * If it is -1, the next method will contain a closing parenthese.
	 * 
	 * @property {Integer} _parenthese
	 * @private
	 */
	private $_parenthese = 0;
	
<span id='Library-Dal-Driver-Mysql-ActiveRecord-property-_lastStmt'>	/**
</span>	 * Last statement used for the query string. This can be '_where' or '_like' for example.
	 * 
	 * @property {String} _lastStmt
	 * @private
	 */
	private $_lastStmt;
		
	private $_select;
	private $_from;
	private $_where;
	private $_insert;
	private $_fields;
	private $_values;
	private $_orderBy;
	private $_limit;
	private $_join;
	
	const INSERT = 'insert';
	const SELECT = 'select';
	const UPDATE = 'update';
	const DELETE = 'delete';
	
	private function _forceArray($array)
	{
		if (isset($array['0']) &amp;&amp; is_array($array['0']))
		{
			$array = $array['0'];
		}
		
		if (!is_array($array))
		{
			$array = array($array);
		}
		
		return $array;
	}
	
<span id='Library-Dal-Driver-Mysql-ActiveRecord-method-_buildQuery'>	/**
</span>	 * Build query
	 * 
	 * @method _buildQuery
	 * @return {}
	 * @private
	 */
	private function _buildQuery()
	{
		$query = '';
		
		switch ($this-&gt;_type)
		{
			case self::INSERT:
				$query = $this-&gt;_buildInsertQuery();
				break;
			case self::SELECT:
				$query = $this-&gt;_buildSelectQuery();
				break;
			case self::UPDATE:
				$query = $this-&gt;_buildUpdateQuery();
				break;
			case self::DELETE:
				$query = $this-&gt;_buildDeleteQuery();
				break;
		}
				
		return $query;
	}
	
	private function _buildInsertQuery()
	{
		$insert = ($this-&gt;_insert) 
			? 'INSERT INTO `' . $this-&gt;_insert . '` (' . $this-&gt;_fields . ') VALUES (' . $this-&gt;_values . ');'
			: '';
		
		$query = $insert;
		
		return $query;
	}
	
	private function _buildSelectQuery()
	{
		$select = ($this-&gt;_select) ? 'SELECT ' . $this-&gt;_select : '';
		$from   = ($this-&gt;_from) ? ' FROM ' . $this-&gt;_from : '';
		$where  = ($this-&gt;_where) ? ' WHERE ' . $this-&gt;_where : '';
		
		$query = $select . $from . $where;
		
		return $query;
	}
	
<span id='Library-Dal-Driver-Mysql-ActiveRecord-method-openParenthese'>	/**
</span>	 * Set an open parenthese '(' for the next method.
	 * 
	 * @method openParenthese
	 */
	public function openParenthese()
	{
		$this-&gt;_parenthese = 1;
		
		return $this;
	}
	
<span id='Library-Dal-Driver-Mysql-ActiveRecord-property-'>	/**
</span>	 * Set an closing parenthese ')' for the next method.
	 */
	public function closeParenthese()
	{
		$this-&gt;{$this-&gt;_lastStmt} .= ' )';
		
		return $this;
	}
	
<span id='Library-Dal-Driver-Mysql-ActiveRecord-method-'>	/**
</span>	 * Insert
	 * 
	 * @param {String} $table
	 * @param {Array} $data
	 * @return {Library.Dal.Driver.Mysql.ActiveRecord} $this
	 */
	public function insert($table, $data = null)
	{
		$this-&gt;_type = self::INSERT;
		
		$this-&gt;_insert = $table;
		
		if ($data !== null &amp;&amp; is_array($data))
		{
			foreach ($data as $key =&gt; $value)
			{
				$param = $this-&gt;_parseParam($key);
				
				$this-&gt;_parameters[] = array(':i_' . $param, $value);
				$this-&gt;_fields .= '`' . $key . '`, ';
				$data[$key] = ':i_' . $param;
			}
			
			$this-&gt;_fields = rtrim($this-&gt;_fields, ', ');
			$this-&gt;_values = implode(', ', $data);
		}
		
		return $this;
	}
	
	public function select()
	{
		$this-&gt;_type = self::SELECT;
		
		$fields = $this-&gt;_forceArray(func_get_args());
		$this-&gt;_select .= implode(', ', $fields) . ' ';
		
		return $this;
	}
	
	public function update()
	{
		$this-&gt;_type = self::UPDATE;	
	}
	
	public function delete()
	{
		$this-&gt;_type = self::DELETE;
	}
	
	public function into($table)
	{
		$this-&gt;_into = $table;
		
		return $this;
	}
	
<span id='Library-Dal-Driver-Mysql-ActiveRecord-method-'>	/**
</span>	 * From
	 * 
	 * @return {Library.Dal.Driver.Mysql.ActiveRecord} $this
	 * @chainable
	 */
	public function from()
	{
		$tables = $this-&gt;_forceArray(func_get_args());
		
		foreach ($tables as $key =&gt; $table)
		{
			$table = '`' . $table . '`';
			
			end($tables);
    		$this-&gt;_from .= ($key === key($tables)) ? $table: $table . ', ';
		}
				
		return $this;
	}
	
<span id='Library-Dal-Driver-Mysql-ActiveRecord-method-_where'>	/**
</span>	 * Handles all the type of where statements. It will prefix the PDO params with 'w_'.
	 * 
	 * @method _where
	 * @param {Array} $where
	 * @param {String} $prefix
	 * @private
	 */
	private function _where($where, $value = null, $prefix = '', $suffix = '')
	{
		// Support for: where('username != ?', 'value');
		if (!is_array($where))
		{
			if ($value !== null)
			{
				$where = array($where =&gt; $value);
			}
			else
			{
				$where = array($where);
			}
		}
		
		if ($this-&gt;_parenthese === 1)
		{
			$prefix = $prefix . ' (';
		}
		
		end($where);
		$endKey = key($where);
		
		foreach ($where as $stmt =&gt; $value)
		{
			$suffix = ($stmt === $endKey) ? '' : ' ' . $suffix;
			
			if(gettype($stmt) === 'integer')
			{
				$stmt = $value;
				$this-&gt;_where .= ' ' . $prefix . ' ' . $stmt . $suffix;
			}
			else
			{
				$test = preg_match('/^([a-zA-Z0-9\_\-\.\s]+)[\s]?([\!\=|\=|\&lt;|\&gt;|\&gt;\=|\&gt;\=]+)[\s]?(.*)$/i', $stmt, $matches);
				
				// Ok, the key of the where is a statement with params or something, let's go fix this to real MySQL
				if ($test)
				{
					$field = trim($matches[1]);
					$this-&gt;bind(':w_' . $field, $value);
					$this-&gt;_where .= ' ' . $prefix . ' `' . $field . '` ' . $matches[2] . str_replace('?', ' :w_' . $field, $matches[3]) . $suffix;
				}
				// Preg match failed, so we think this where is just a key-value pair
				else
				{
					$this-&gt;bind(':w_' . $stmt, $value);
					$this-&gt;_where .= ' ' . $prefix . ' `' . $stmt . '`' . ' = :w_' . $stmt . $suffix;
				}
			}
		}
		
		$this-&gt;_methodEnded(__FUNCTION__, '_where');
	}
	
<span id='Library-Dal-Driver-Mysql-ActiveRecord-method-where'>	/**
</span>	 * Where statement
	 * 
	 * Use this method to begin a WHERE statement. By default it will continue using AND as suffix. So if you will
	 * enter the following:
	 * 
	 * 	$ar-&gt;select('*')
	 * 	   -&gt;from('users')
	 * 	   -&gt;where(array(
	 * 			'username' =&gt; 'Hotel',
	 * 			'age'	   =&gt; 18,
	 * 			'gender'   =&gt; 'male'
	 * 		));
	 * 
	 * This will produce the following MySQL string:
	 * 
	 * 	SELECT * FROM `users` WHERE `username` = :w_username AND `age` = :w_age AND `gender` = :w_gender
	 * 
	 * You can also use your own functions and stuff:
	 * 
	 * 	where(array(
	 * 		'age IN (18, 19, 20)' =&gt; null 
	 * 	));
	 * 
	 * @method where
	 * @param {Array} $where
	 * @return {Library.Dal.Driver.Mysql.ActiveRecord} $this
	 * @return ActiveRecord
	 * @chainable
	 */
	public function where($where, $value = null)
	{
		$this-&gt;_where($where, $value, '', 'AND');
		
		return $this;
	}
	
<span id='Library-Dal-Driver-Mysql-ActiveRecord-method-orWhere'>	/**
</span>	 * Or where statement
	 * 
	 * Use this method if you want to continue your where statement with the OR operator. See the documentation
	 * of the **{@link Library.Dal.Driver.Mysql.ActiveRecord#where}** method for more information.
	 * 
	 * @method orWhere
	 * @param {Array} $where
	 * @param {Array} $where
	 * @return {Library.Dal.Driver.Mysql.ActiveRecord} $this
	 * @chainable
	 */
	public function orWhere($where, $value = null)
	{
		$this-&gt;_where($where, $value, 'OR');
		
		return $this;
	}
	
	public function andWhere($where, $value = null)
	{
		$this-&gt;_where($where, $value, 'AND');

		return $this;
	}
	
	public function xorWhere($where, $value = null)
	{
		$this-&gt;_where($where, $value, 'XOR');
		
		return $this;
	}
	
	public function orderBy()
	{
		$fields = $this-&gt;_forceArray(func_get_args());
		$this-&gt;_orderBy .= implode(', ', $fields);
		
		return $this;
	}
	
	public function getParameters()
	{
		return $this-&gt;_parameters;
	}
	
	public function limit()
	{
		
	}
	
	public function join()
	{
		
	}
	
	public function bind($key, $value, $dataType = \Library\Dal\DataType::String)
	{
		$this-&gt;_parameters[] = array($key, $value, $dataType);
		
		return $this;
	}
	
<span id='Library-Dal-Driver-Mysql-ActiveRecord-method-_methodEnded'>	/**
</span>	 * Called when a ActiveRecord method has ended.
	 * 
	 * @method _methodEnded
	 * @param {String} $method 		Method name which called this method
	 * @param {String} $queryStmt	Query statement name (_where, _like etc.)
	 * @private
	 */
	private function _methodEnded($method, $queryStmt)
	{
		$this-&gt;_lastStmt = $queryStmt;
		
		// Set the parenthese to 0 so the next method wont begin with a parenthese
		$this-&gt;_parenthese = 0;
	}
	
	private function _parseParam($param)
	{
		$param = str_replace(' ', '_', $param);
		$param = str_replace('-', '_', $param);
		
		return $param;
	}
	
	public function __toString()
	{
		return (string)$this-&gt;_buildQuery();
	}
}</pre>
</body>
</html>
